package com.pubinfo.passbook.xml;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.pubinfo.passbook.common.utils.XmlTool;
import com.pubinfo.passbook.common.entity.TPassbook;
import org.dom4j.*;

import java.util.List;

/**
 * Created by chengsheng on 2015/8/19.
 */
public class Xml2Json {
  //public static void main(String[] args) throws Exception {
//    String xmlStr= readFile("D:/ADA/et/Issue_20130506_back.xml");
//    Document doc= DocumentHelper.parseText(xmlStr);
//    JSONObject json=new JSONObject();
//    dom4j2Json(doc.getRootElement(),json);
//    System.out.println("xml2Json:"+json.toJSONString());
//    List<TPassbook> list = new ArrayList<>();
//    TPassbook passbook = new TPassbook();
//    passbook.setEInvoiceId("111");
//    list.add(passbook);
//    System.out.println(list);
//    set(list);
//    System.out.println(list);
  //  toJson();
  // }
  
  private static void set(List<TPassbook> list) {
    list.stream().forEach(tPassbook -> {
      tPassbook.setClassName("111");
    });
  }
  
  public static void toJson() {
    String xml = "<?xml version=\"1.0\" encoding=\"gb2312\"?>\n" +
        "\n" +
        "<EInvoice>\n" +
        "  <Header>\n" +
        "    <EInvoiceTag>CZ-EI-33</EInvoiceTag>\n" +
        "    <EInvoiceID>7166565300-12106033</EInvoiceID>\n" +
        "    <Version>1.1.0</Version> \n" +
        "  </Header>\n" +
        "  <EInvoiceData>\n" +
        "    <Main>\n" +
        "      <EInvoiceName>浙江省医疗门诊收费票据（电子）</EInvoiceName>\n" +
        "      <EInvoiceCode>33060121</EInvoiceCode>\n" +
        "      <EInvoiceNumber>0035656617</EInvoiceNumber>\n" +
        "      <RandomNumber>886449</RandomNumber>\n" +
        "      <EInvoiceSpecimenCode>3306012001</EInvoiceSpecimenCode>\n" +
        "      <SupervisorAreaCode>330000</SupervisorAreaCode>\n" +
        "      <TotalAmount>30.00</TotalAmount>\n" +
        "      <IssueDate>20210127</IssueDate>\n" +
        "      <IssueTime>11:32:31</IssueTime>\n" +
        "      <InvoicingParty>\n" +
        "        <InvoicingPartyCode>123300004700032309</InvoicingPartyCode>\n" +
        "        <InvoicingPartyName>浙江大学医学院附属第二医院</InvoicingPartyName> \n" +
        "      </InvoicingParty>\n" +
        "      <PayerParty>\n" +
        "        <PayerPartyType>1</PayerPartyType>\n" +
        "        <PayerPartyCode>330382198909290024</PayerPartyCode>\n" +
        "        <PayerPartyName>陈亦新</PayerPartyName> \n" +
        "      </PayerParty>\n" +
        "      <BizCode>84115562</BizCode>\n" +
        "      <Remark>[普通门诊]</Remark>\n" +
        "      <HandlingPerson>ZZX358</HandlingPerson>\n" +
        "      <Checker>ZZX358</Checker>\n" +
        "      <MainExt>\n" +
        "        <Gender>女</Gender>\n" +
        "        <Age>32</Age>\n" +
        "        <MedicalType>门诊</MedicalType>\n" +
        "        <PatientNumber>0A02795583</PatientNumber>\n" +
        "        <MedicalDate>20210127</MedicalDate>\n" +
        "        <OrgType>三甲</OrgType>\n" +
        "        <MedicalInsuranceType>省直医保 在职非公务员</MedicalInsuranceType>\n" +
        "        <MedicalInsuranceID>12070807</MedicalInsuranceID>\n" +
        "        <FundPayAmount>0.00</FundPayAmount>\n" +
        "        <FundPayAmountInfo>公务员补助:0.00 统筹基金:0.00 大病基金:0.00超医保支付费用:0.00 其中近亲属历账:0.00其中大病用药:0.00 此前起付线累计:820.06 起付线:15.00</FundPayAmountInfo>\n" +
        "        <FundDJJZAmount>0.00</FundDJJZAmount>\n" +
        "        <OtherPayAmount>0.00</OtherPayAmount>\n" +
        "        <AccountPayAmount>30.00</AccountPayAmount>\n" +
        "        <IndividualAccountCurrPayment>0.00</IndividualAccountCurrPayment>\n" +
        "        <IndividualAccountPrevPayment>30.00</IndividualAccountPrevPayment>\n" +
        "        <OwnPayAmount>0.00</OwnPayAmount>\n" +
        "        <OwnPayAmountInfo>实收金额:0.00 其中现金:0.00本院记账:0.00现金支付:0.00(自理:0.00 自费:15.00 自付:0.00)</OwnPayAmountInfo>\n" +
        "        <SelfpaymentAmount>0.00</SelfpaymentAmount>\n" +
        "        <SelfpaymentCost>15.00</SelfpaymentCost>\n" +
        "        <SelfpaymentCare>0.00</SelfpaymentCare>\n" +
        "        <IndividualAccountCurrBalance>0.00</IndividualAccountCurrBalance>\n" +
        "        <IndividualAccountPrevBalance>227.17</IndividualAccountPrevBalance>\n" +
        "        <PhoneNumber>13336185586</PhoneNumber>\n" +
        "        <CaseNumber>0A02795583</CaseNumber> \n" +
        "      </MainExt> \n" +
        "    </Main>\n" +
        "    <Details>\n" +
        "      <Item>\n" +
        "        <ItemCode>201080410</ItemCode>\n" +
        "        <ItemName>一般诊疗费</ItemName>\n" +
        "        <ItemQuantity>2</ItemQuantity>\n" +
        "        <ItemAmount>30.00</ItemAmount>\n" +
        "        <ItemExt>\n" +
        "          <ItemAmountSelf>15.00</ItemAmountSelf>\n" +
        "          <ItemAmountPercent>50.00</ItemAmountPercent> \n" +
        "        </ItemExt> \n" +
        "      </Item> \n" +
        "    </Details>\n" +
        "    <AuxDetails>\n" +
        "      <AuxItem>\n" +
        "        <AuxItemRelatedCode>201080410</AuxItemRelatedCode>\n" +
        "        <AuxItemRelatedName>一般诊疗费</AuxItemRelatedName>\n" +
        "        <AuxItemCode>1000000000000001</AuxItemCode>\n" +
        "        <AuxItemName>专家门诊诊查费（正高）加收2021-01-27</AuxItemName>\n" +
        "        <AuxItemQuantity>1</AuxItemQuantity>\n" +
        "        <AuxItemUnit>次</AuxItemUnit>\n" +
        "        <AuxItemStd>15.00</AuxItemStd>\n" +
        "        <AuxItemAmount>15.00</AuxItemAmount>\n" +
        "        <AuxItemRemark>丙/15.00/1.00</AuxItemRemark>\n" +
        "        <AuxItemType>丙</AuxItemType>\n" +
        "        <AuxItemAmountSelf>15.00</AuxItemAmountSelf>\n" +
        "        <AuxItemAmountPercent>1.00</AuxItemAmountPercent> \n" +
        "      </AuxItem>\n" +
        "      <AuxItem>\n" +
        "        <AuxItemRelatedCode>201080410</AuxItemRelatedCode>\n" +
        "        <AuxItemRelatedName>一般诊疗费</AuxItemRelatedName>\n" +
        "        <AuxItemCode>f11020000101</AuxItemCode>\n" +
        "        <AuxItemName>门诊诊查费2021-01-27</AuxItemName>\n" +
        "        <AuxItemQuantity>1</AuxItemQuantity>\n" +
        "        <AuxItemUnit>次</AuxItemUnit>\n" +
        "        <AuxItemStd>15.00</AuxItemStd>\n" +
        "        <AuxItemAmount>15.00</AuxItemAmount>\n" +
        "        <AuxItemRemark>甲/0.00/0.00</AuxItemRemark>\n" +
        "        <AuxItemType>甲</AuxItemType>\n" +
        "        <AuxItemAmountSelf>0.00</AuxItemAmountSelf>\n" +
        "        <AuxItemAmountPercent>0.00</AuxItemAmountPercent> \n" +
        "      </AuxItem> \n" +
        "    </AuxDetails> \n" +
        "  </EInvoiceData>\n" +
        "  <EInvoiceSignature>\n" +
        "    <Signature id=\"InvoicingParty\">\n" +
        "      <SignedInfo>\n" +
        "        <Reference URI=\"/EInvoice/Header | /EInvoice/EInvoiceData\"/>\n" +
        "        <SignatureAlgorithm>SHA-256</SignatureAlgorithm>\n" +
        "        <SignatureFormat>DETACH</SignatureFormat>\n" +
        "      </SignedInfo>\n" +
        "      <SignatureTime>27 Jan 2021 03:33:20 GMT</SignatureTime>\n" +
        "      <SignatureValue>MIIFaAYJKoZIhvcNAQcCoIIFWTCCBVUCAQExCTAHBgUrDgMCGjALBgkqhkiG9w0BBwGgggQRMIIEDTCCAvWgAwIBAgIIHDJFs50d0nIwDQYJKoZIhvcNAQEFBQAwSjELMAkGA1UEBhMCQ04xDDAKBgNVBAoTA01PRjEtMCsGA1UEAxMkUHJpdmF0ZSBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkgT2YgTU9GMB4XDTE3MDkyNTA5MTQ1MVoXDTI2MTIxMjA5MTQxNlowfjELMAkGA1UEBhMCQ04xDDAKBgNVBAoMA01PRjELMAkGA1UEBwwCMDAxCzAJBgNVBAcMAjAwMQswCQYDVQQLDAIwNDERMA8GA1UEDAwIMjAxNzA5MjUxJzAlBgNVBAMMHui0ouaUv+eUteWtkOelqOaNruS4muWKoea1i+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TjEMMAoGA1UEChMDTU9GMS0wKwYDVQQDEyRQcml2YXRlIENlcnRpZmljYXRlIEF1dGhvcml0eSBPZiBNT0YCCBwyRbOdHdJyMAcGBSsOAwIaMAsGCSqGSIb3DQEBAQSBgIERJycdx7Y+Ksg/Op99qJVGda+BILL25mtqPGrO6Sq6wS3BV04c2c/bbnhn3XK0bCp2d4vqMrxBGkkjsQCxxv94iUck8/znxyTsqCkEfqlJG2JlCzd8MKjJhtUbgohzAvxvmV+wPjdUwO4XtuJLdDJYD0n0UEhaSrDpi0IM/A39oScwJQYLKwYBBAGB/mIBEwExFgQUx+aKGN3i1lxpjkYL4SmeCglLSRY=</SignatureValue>\n" +
        "      <KeyInfo>\n" +
        "        <SerialNumber>1c3245b39d1dd272</SerialNumber>\n" +
        "        <X509IssuerName>CN=Private Certificate Authority Of MOF,O=MOF,C=CN</X509IssuerName>\n" +
        "      </KeyInfo>\n" +
        "    </Signature>\n" +
        "    <Signature id=\"SupervisorParty\">\n" +
        "      <SignedInfo>\n" +
        "        <Reference URI=\"sha256(/EInvoice/Header | /EInvoice/EInvoiceData) | /EInvoice/EInvoiceSignature/Signature[@id='InvoicingParty']\"/>\n" +
        "        <SignatureAlgorithm>SHA256WithRSA</SignatureAlgorithm>\n" +
        "        <SignatureFormat>DETACH</SignatureFormat>\n" +
        "      </SignedInfo>\n" +
        "      <SignatureTime>27 Jan 2021 03:33:21 GMT</SignatureTime>\n" +
        "      <SignatureValue>MIIFlgYJKoZIhvcNAQcCoIIFhzCCBYMCAQExDzANBglghkgBZQMEAgEFADALBgkqhkiG9w0BBwGgggRcMIIEWDCCA0CgAwIBAgIIMHAm4/AGdPAwDQYJKoZIhvcNAQEFBQAwSjELMAkGA1UEBhMCQ04xDDAKBgNVBAoTA01PRjEtMCsGA1UEAxMkUHJpdmF0ZSBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkgT2YgTU9GMB4XDTE0MTIxMjAzNTEzNFoXDTIzMDIyODAzNTEzNFowgY4xCzA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X1arpOYXffD8gvMHUg8sLIfT97JN597AAeScESsWA/OcyIFUVosl/5zBmSaKK/u7S2fHc6H0vhgfLrdxmQQueswL96nZD9foiSDc33Q5HRGNvP/kQKVTkCsAAxeixHfLLfegYuRz2goCKq52naUUS1GjzcyPfsvZug5nMeKc2leNhZLT2ZHyWQmghQP0MYuLrENhWHe2EAQDr+lPFEaQyWUf0/nwYvUxQMYH/MIH8AgEBMFYwSjELMAkGA1UEBhMCQ04xDDAKBgNVBAoTA01PRjEtMCsGA1UEAxMkUHJpdmF0ZSBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkgT2YgTU9GAggwcCbj8AZ08DANBglghkgBZQMEAgEFADANBgkqhkiG9w0BAQEFAASBgEpPvvmHc2vBZRfOZQ15HCLFXNosPc3HS/6XHb5aK2P3Y1G7lU2JeKE72Sm+cvHfTPd9jE/ggZal9n00HlWBq9yWii7N46kyOMjRzSOj49kDWKSEyOqHZVierJxkMht0tOsIGhEWG+gp5vxgE0Htx5mIK0MYdf3+OqPb7n0pjdhv</SignatureValue>\n" +
        "      <KeyInfo>\n" +
        "        <SerialNumber>30 70 26 E3 F0 06 74 F0</SerialNumber>\n" +
        "        <X509IssuerName>cn=Private Certificate Authority Of MOF o=MOF c=CN</X509IssuerName>\n" +
        "      </KeyInfo>\n" +
        "    </Signature>\n" +
        "  </EInvoiceSignature>\n" +
        "</EInvoice>\n" +
        "\n";
    System.out.println(XmlTool.xml2json(xml));
  }
  
  /**
   * xml转json
   *
   * @param xmlStr
   * @return
   * @throws DocumentException
   */
  public static JSONObject xml2Json(String xmlStr) throws DocumentException {
    Document doc = DocumentHelper.parseText(xmlStr);
    JSONObject json = new JSONObject();
    dom4j2Json(doc.getRootElement(), json);
    return json;
  }
  
  /**
   * xml转json
   *
   * @param element
   * @param json
   */
  public static void dom4j2Json(Element element, JSONObject json) {
    //如果是属性
    for (Object o : element.attributes()) {
      Attribute attr = (Attribute) o;
      if (!isEmpty(attr.getValue())) {
        json.put("@" + attr.getName(), attr.getValue());
      }
    }
    List<Element> chdEl = element.elements();
    if (chdEl.isEmpty() && !isEmpty(element.getText())) {//如果没有子元素,只有一个值
      json.put(element.getName(), element.getText());
    }
    
    for (Element e : chdEl) {//有子元素
      if (!e.elements().isEmpty()) {//子元素也有子元素
        JSONObject chdjson = new JSONObject();
        dom4j2Json(e, chdjson);
        Object o = json.get(e.getName());
        if (o != null) {
          JSONArray jsona = null;
          if (o instanceof JSONObject) {//如果此元素已存在,则转为jsonArray
            JSONObject jsono = (JSONObject) o;
            json.remove(e.getName());
            jsona = new JSONArray();
            jsona.add(jsono);
            jsona.add(chdjson);
          }
          if (o instanceof JSONArray) {
            jsona = (JSONArray) o;
            jsona.add(chdjson);
          }
          json.put(e.getName(), jsona);
        } else {
          if (!chdjson.isEmpty()) {
            json.put(e.getName(), chdjson);
          }
        }
        
      } else {//子元素没有子元素
        for (Object o : element.attributes()) {
          Attribute attr = (Attribute) o;
          if (!isEmpty(attr.getValue())) {
            json.put("@" + attr.getName(), attr.getValue());
          }
        }
        if (!e.getText().isEmpty()) {
          json.put(e.getName(), e.getText());
        }
      }
    }
  }
  
  public static boolean isEmpty(String str) {
    
    return str == null || str.trim().isEmpty() || "null".equals(str);
  }
}